<template>
  <div class="script-generation">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">
        <el-icon><DocumentCopy /></el-icon>
        脚本生成
      </h1>
      <p class="page-description">生成适合您系统的自动化部署脚本</p>
    </div>

    <el-row :gutter="20">
      <!-- 左侧：配置区域 -->
      <el-col :xs="24" :lg="10">
        <!-- 已选择的软件 -->
        <el-card class="config-card">
          <template #header>
            <div class="card-header">
              <el-icon><Box /></el-icon>
              <span>已选择的软件 ({{ selectedCount }})</span>
            </div>
          </template>

          <div v-if="selectedCount === 0" class="empty-software">
            <el-empty description="还没有选择任何软件">
              <el-button type="primary" @click="goToSoftwareSelection">
                去选择软件
              </el-button>
            </el-empty>
          </div>

          <div v-else class="software-list">
            <div
              v-for="software in selectedSoftware"
              :key="software.id"
              class="software-item"
            >
              <div class="software-info">
                <div class="software-name">{{ software.displayName }}</div>
                <div class="software-version">版本: {{ software.version }}</div>
              </div>
              <el-tag :type="getCategoryType(software.category)" size="small">
                {{ software.category }}
              </el-tag>
            </div>
          </div>
        </el-card>

        <!-- 脚本配置 -->
        <el-card class="config-card">
          <template #header>
            <div class="card-header">
              <el-icon><Setting /></el-icon>
              <span>脚本配置</span>
            </div>
          </template>

          <el-form label-width="120px">
            <el-form-item label="操作系统">
              <el-select v-model="osConfig" @change="handleOsChange">
                <el-option label="Windows" value="windows">
                  <el-icon><Monitor /></el-icon>
                  <span style="margin-left: 8px;">Windows</span>
                </el-option>
                <el-option label="Linux" value="linux">
                  <el-icon><Monitor /></el-icon>
                  <span style="margin-left: 8px;">Linux</span>
                </el-option>
                <el-option label="macOS" value="macos">
                  <el-icon><Monitor /></el-icon>
                  <span style="margin-left: 8px;">macOS</span>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="安装路径">
              <el-input v-model="installPathConfig" placeholder="请输入安装路径" />
            </el-form-item>

            <el-form-item label="镜像地区">
              <el-select v-model="mirrorRegionConfig">
                <el-option label="中国大陆" value="CN" />
                <el-option label="美国" value="US" />
                <el-option label="欧洲" value="EU" />
              </el-select>
            </el-form-item>

            <el-form-item label="高级选项">
              <div class="advanced-options">
                <el-checkbox v-model="enableResumeConfig">
                  启用断点续传
                </el-checkbox>
                <el-checkbox v-model="enableVerificationConfig">
                  启用环境验证
                </el-checkbox>
                <el-checkbox v-model="enableAutoPathConfig">
                  自动配置环境变量
                </el-checkbox>
              </div>
            </el-form-item>
          </el-form>

          <div class="generate-actions">
            <el-button
              type="primary"
              size="large"
              @click="generateScript"
              :loading="generating"
              :disabled="selectedCount === 0"
            >
              <el-icon><Tools /></el-icon>
              生成脚本
            </el-button>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：脚本预览 -->
      <el-col :xs="24" :lg="14">
        <el-card class="script-preview-card">
          <template #header>
            <div class="card-header">
              <el-icon><Document /></el-icon>
              <span>脚本预览</span>
              <div class="header-actions" v-if="generatedScript">
                <el-button size="small" @click="copyScript">
                  <el-icon><DocumentCopy /></el-icon>
                  复制脚本
                </el-button>
                <el-button size="small" @click="downloadScript">
                  <el-icon><Download /></el-icon>
                  下载脚本
                </el-button>
              </div>
            </div>
          </template>

          <div v-if="!generatedScript" class="empty-script">
            <el-empty description="还没有生成脚本">
              <p class="hint">配置好参数后点击"生成脚本"按钮</p>
            </el-empty>
          </div>

          <div v-else class="script-content">
            <!-- 脚本信息 -->
            <div class="script-info">
              <el-descriptions :column="2" size="small" border>
                <el-descriptions-item label="文件名">
                  {{ generatedScript.fileName }}
                </el-descriptions-item>
                <el-descriptions-item label="操作系统">
                  {{ scriptConfig.os }}
                </el-descriptions-item>
                <el-descriptions-item label="软件数量">
                  {{ selectedCount }}
                </el-descriptions-item>
                <el-descriptions-item label="脚本大小">
                  {{ formatFileSize(generatedScript.scriptContent?.length || 0) }}
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 脚本代码 -->
            <div class="script-code">
              <el-input
                v-model="generatedScript.scriptContent"
                type="textarea"
                :rows="20"
                readonly
                placeholder="脚本内容将在这里显示..."
              />
            </div>

            <!-- 执行指南 -->
            <div class="execution-guide">
              <h3>执行指南</h3>
              <div class="guide-content">
                <pre>{{ generatedScript.executionGuide }}</pre>
              </div>
            </div>

            <!-- 系统要求 -->
            <div class="requirements" v-if="generatedScript.requirements">
              <h3>系统要求</h3>
              <ul>
                <li v-for="req in generatedScript.requirements" :key="req">
                  {{ req }}
                </li>
              </ul>
            </div>

            <!-- 注意事项 -->
            <div class="warnings" v-if="generatedScript.warnings">
              <h3>注意事项</h3>
              <el-alert
                v-for="warning in generatedScript.warnings"
                :key="warning"
                :title="warning"
                type="warning"
                :closable="false"
                style="margin-bottom: 8px;"
              />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useSoftwareStore } from '../stores/software'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import {
  DocumentCopy, Box, Setting, Monitor, Tools, Document,
  Download
} from '@element-plus/icons-vue'

const router = useRouter()
const softwareStore = useSoftwareStore()
const userStore = useUserStore()

// 响应式数据
const generating = ref(false)

// 使用computed属性与store同步配置
const scriptConfig = computed({
  get: () => softwareStore.getScriptConfig(),
  set: (value) => softwareStore.updateScriptConfig(value)
})

// 为每个配置项创建单独的computed属性以确保响应式更新
const osConfig = computed({
  get: () => scriptConfig.value.os,
  set: (value) => softwareStore.updateScriptConfig({ os: value })
})

const installPathConfig = computed({
  get: () => scriptConfig.value.installPath,
  set: (value) => softwareStore.updateScriptConfig({ installPath: value })
})

const mirrorRegionConfig = computed({
  get: () => scriptConfig.value.mirrorRegion,
  set: (value) => softwareStore.updateScriptConfig({ mirrorRegion: value })
})

const enableResumeConfig = computed({
  get: () => scriptConfig.value.enableResume,
  set: (value) => softwareStore.updateScriptConfig({ enableResume: value })
})

const enableVerificationConfig = computed({
  get: () => scriptConfig.value.enableVerification,
  set: (value) => softwareStore.updateScriptConfig({ enableVerification: value })
})

const enableAutoPathConfig = computed({
  get: () => scriptConfig.value.enableAutoPath,
  set: (value) => softwareStore.updateScriptConfig({ enableAutoPath: value })
})

// 计算属性
const selectedSoftware = computed(() => softwareStore.selectedSoftware)
const selectedCount = computed(() => softwareStore.selectedCount)
const generatedScript = computed(() => softwareStore.generatedScript)

// 生命周期
onMounted(() => {
  // 确保配置已初始化
  const currentConfig = softwareStore.getScriptConfig()
  if (!currentConfig.os) {
    softwareStore.updateScriptConfig({ os: 'windows' })
  }
  if (!currentConfig.installPath) {
    softwareStore.updateScriptConfig({ installPath: 'C:\\DevEnv' })
  }
})

// 监听配置变化已通过computed属性自动处理

// 方法
const handleOsChange = (os) => {
  // 根据操作系统设置默认安装路径
  let defaultPath
  switch (os) {
    case 'windows':
      defaultPath = 'C:\\DevEnv'
      break
    case 'linux':
      defaultPath = '/opt/devenv'
      break
    case 'macos':
      defaultPath = '/Applications/DevEnv'
      break
    default:
      defaultPath = 'C:\\DevEnv'
  }

  softwareStore.updateScriptConfig({
    os: os,
    installPath: defaultPath
  })
}

const generateScript = async () => {
  if (selectedCount.value === 0) {
    ElMessage.warning('请先选择要安装的软件')
    return
  }

  generating.value = true
  try {
    // 配置已通过computed属性自动同步到store
    await softwareStore.generateScript()
    ElMessage.success('脚本生成成功！')
    
    // 记录脚本生成活动
    try {
      const activityData = {
        os: osConfig.value,
        software_count: selectedCount.value,
        install_path: installPathConfig.value
      }
      console.log('准备记录脚本生成活动:', activityData)
      await userStore.recordActivity('script_generation', activityData)
      console.log('脚本生成活动记录成功:', activityData)
    } catch (error) {
      console.warn('记录脚本生成活动失败:', error)
    }
  } catch (error) {
    ElMessage.error('脚本生成失败: ' + error.message)
  } finally {
    generating.value = false
  }
}

const copyScript = async () => {
  try {
    await navigator.clipboard.writeText(generatedScript.value.scriptContent)
    ElMessage.success('脚本已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败，请手动复制')
  }
}

const downloadScript = () => {
  const content = generatedScript.value.scriptContent
  const fileName = generatedScript.value.fileName
  
  const blob = new Blob([content], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  
  const link = document.createElement('a')
  link.href = url
  link.download = fileName
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  
  URL.revokeObjectURL(url)
  ElMessage.success('脚本下载成功')
}

const goToSoftwareSelection = () => {
  router.push('/software')
}

const getCategoryType = (category) => {
  const typeMap = {
    'IDE': 'primary',
    'Runtime': 'success',
    'Database': 'warning',
    'Tool': 'info',
    'Build Tool': 'danger'
  }
  return typeMap[category] || 'info'
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}
</script>

<style scoped>
.script-generation {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-title {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
}

.page-description {
  color: #7f8c8d;
  font-size: 16px;
}

.config-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.header-actions {
  margin-left: auto;
  display: flex;
  gap: 8px;
}

.empty-software {
  text-align: center;
  padding: 40px 20px;
}

.software-list {
  max-height: 200px;
  overflow-y: auto;
}

.software-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  margin-bottom: 8px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #ebeef5;
}

.software-info {
  flex: 1;
}

.software-name {
  font-size: 14px;
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 4px;
}

.software-version {
  font-size: 12px;
  color: #7f8c8d;
}

.advanced-options {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.generate-actions {
  text-align: center;
  margin-top: 20px;
}

.script-preview-card {
  height: fit-content;
}

.empty-script {
  text-align: center;
  padding: 60px 20px;
}

.hint {
  color: #7f8c8d;
  font-size: 14px;
  margin-top: 8px;
}

.script-content {
  max-height: 800px;
  overflow-y: auto;
}

.script-info {
  margin-bottom: 20px;
}

.script-code {
  margin-bottom: 20px;
}

.script-code :deep(.el-textarea__inner) {
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
}

.execution-guide,
.requirements,
.warnings {
  margin-bottom: 20px;
}

.execution-guide h3,
.requirements h3,
.warnings h3 {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.guide-content {
  background: #f8f9fa;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  padding: 16px;
}

.guide-content pre {
  margin: 0;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.5;
  color: #2c3e50;
  white-space: pre-wrap;
}

.requirements ul {
  margin: 0;
  padding-left: 20px;
}

.requirements li {
  margin-bottom: 4px;
  color: #2c3e50;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .script-generation {
    padding: 0 10px;
  }

  .page-title {
    font-size: 24px;
  }

  .header-actions {
    flex-direction: column;
    gap: 4px;
  }
}

@media (max-width: 768px) {
  .advanced-options {
    gap: 12px;
  }

  .script-code :deep(.el-textarea__inner) {
    font-size: 11px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .header-actions {
    align-self: stretch;
  }
}
</style>
